<template>
  <div v-loading="loading" class="networks" element-loading-text="加载中...">
    <div class="title_header">
      <div class="line"></div>
      <h4 class="text">库存查询</h4>
    </div>
    <div class="line_"></div>
    <div class="main">
      <div>
        <div class="sidebar">
          <div class="header">
            <h4>库存分类</h4>
          </div>
          <div class="line_min"></div>
          <div class="trees_container">
            <div
              :class="{ tree_item: true, active_tree_item: !isTypeId }"
              @click="onSelectGoodTypeTree({ id: 0, name: '' }, { level: 0 })"
            >
              {{ dataType[0].name }}</div
            >
            <div class="tree_box">
              <el-tree
                :accordion="true"
                style="max-width: 100%"
                :data="dataType[0].childData"
                :props="defaultProps"
                node-key="id"
                @node-click="onSelectGoodTypeTree"
              >
                <template #default="{ node, data }">
                  <span
                    class="custom-tree-node"
                    :class="{ is_active_tree_item: isTypeId == data.id, is_disable: data.status }"
                  >
                    <span style="height: 100%">
                      <ShowTooltip
                        placement="top"
                        :ref-name="'testName' + node.id"
                        class-name="is_textClass"
                        :content="node.label"
                        :is-text="true"
                        :color="isTypeId == data.id ? '#fff' : data.status ? '#999' : '#666'"
                        :size="12"
                        :offset="5"
                        :show-after="300"
                      ></ShowTooltip>
                    </span>
                    <div
                      v-if="editshow"
                      style="
                        position: absolute;
                        right: 0;
                        display: flex;
                        gap: 8px;
                        z-index: 999;
                        padding-right: 2px;
                      "
                    >
                      <el-icon size="14" @click.stop="onEditGoodType(node, data)">
                        <EditPen />
                      </el-icon>
                      <el-icon size="14" @click.stop="onDelGoodType(node, data)">
                        <Delete />
                      </el-icon>
                    </div>
                  </span>
                </template>
              </el-tree>
            </div>
          </div>
        </div>
      </div>
      <div class="table_list">
        <div class="header">
          <div class="btn_group"> </div>
          <div class="search">
            <span style="display: flex; align-items: center">查询日期:</span>
            <el-date-picker
              v-model="dayTime"
              value-format="YYYY-MM-DD"
              :readonly="true"
              style="width: 120px"
              type="date"
              placeholder="查询日期"
              disabled
            />
            <span style="display: flex; align-items: center">查询条件:</span>
            <el-select
              v-model="searchVo.selectType"
              placeholder="汇总数据"
              @change="getStoneListRows()"
            >
              <el-option
                v-for="item in dataTotal"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <!-- <el-select
              v-model="searchVo.storeType"
              placeholder="仓库类型"
              clearable
              @change="getStoneListRows()"
            >
              <el-option
                v-for="item in storeType"
                :key="item.value"
                :label="item.title"
                :value="item.value"
              />
            </el-select> -->
            <el-select
              v-model="searchVo.storeIds"
              placeholder="仓库名称"
              :loading="getstoneOptionsLoading"
              clearable
              multiple
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="1"
              @change="getStoneListRows"
            >
              <template #header>
                <div style="display: flex; gap: 6px">
                  <el-input
                    v-model.trim="getstoneOptionsKeyword"
                    placeholder="请输入仓库名称"
                    @keyup.enter="getstoneOptions"
                  />
                  <h-plain-button @click="getstoneOptions">搜索</h-plain-button>
                </div>
              </template>
              <el-option
                v-for="item in stoneOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <!-- <el-select
              v-model="searchVo.goodsType"
              placeholder="物料类型"
              clearable
              @change="getStoneListRows()"
            >
              <el-option value="1" label="成品" />
              <el-option value="2" label="物料" />
            </el-select> -->
            <!-- <el-select
              v-model="searchVo.brandId"
              placeholder="物料品牌"
              clearable
              :loading="getBrandOptionsLoading"
              @change="getStoneListRows()"
            >
              <template #header>
                <div style="display: flex; gap: 6px">
                  <el-input
                    v-model.trim="getBrandOptionsKeyword"
                    placeholder="请输入品牌名称"
                    @keyup.enter="getBrandOptions"
                  />
                  <h-plain-button @click="getBrandOptions">搜索</h-plain-button>
                </div>
              </template>
              <el-option
                v-for="item in brandOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select> -->
            <el-input
              v-model.trim="searchVo.keyword"
              placeholder="物料名称/型号/规格/编号"
              class="keyword"
              clearable
              @keyup.enter="getStoneListRows()"
              @clear="getStoneListRows()"
            />
            <div class="btn_group">
              <HButton type="primary" @click="getStoneListRows()">
                <el-icon class="mr5">
                  <Search />
                </el-icon>
                搜索
              </HButton>
              <HButton @click="onReset()">
                <el-icon class="mr5">
                  <RefreshRight />
                </el-icon>
                重置
              </HButton>
            </div>
          </div>
        </div>
        <div class="table">
          <el-table
            v-show="searchVo.selectType == 1"
            :border="true"
            height="100%"
            style="position: absolute"
            stripe
            resizable
            :data="tableDataList"
            show-summary
            :summary-method="getGoodAndWarrantySummary"
            @selection-change="handleChange"
            @row-dblclick="goEdit"
          >
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
            <!-- <el-table-column type="selection" width="40" fixed /> -->
            <el-table-column fixed type="index" label="序号" width="49" :align="'center'" />
            <el-table-column show-overflow-tooltip prop="goodsCode" label="物料编号" width="120" />
            <el-table-column show-overflow-tooltip prop="goodsName" label="物料名称" width="120" />
            <!-- <el-table-column show-overflow-tooltip prop="goodsModel" label="物料型号" width="73" /> -->
            <el-table-column
              show-overflow-tooltip
              prop="goodsSpecName"
              label="物料规格"
              width="97"
            />
            <!-- <el-table-column show-overflow-tooltip prop="goodsType" label="物料类型" width="73">
              <template #default="i">
                <span>{{
                  i.row.goodsType == 1 ? '成品' : i.row.goodsType == 2 ? '物料' : ''
                }}</span>
              </template>
            </el-table-column> -->
            <!-- <el-table-column show-overflow-tooltip prop="goodsBrand" label="物料品牌" width="104" /> -->
            <el-table-column show-overflow-tooltip label="物料分类" width="104">
              <template #default="i">
                {{ [i.row.type, i.row.twoType, i.row.threeType].join('-') }}
              </template>
            </el-table-column>
            <!-- <el-table-column show-overflow-tooltip prop="storeCode" label="仓库编号" width="120" /> -->
            <!-- 是否为核心件 -->
            <el-table-column label="核心件" width="90">
              <template #header>
                <el-dropdown trigger="click">
                  <div style="display: flex; align-items: center">
                    <span
                      :style="{
                        color: searchVo.coreMaterial === null ? '' : '#007cff',
                      }"
                    >
                      核心件
                    </span>
                    <el-icon class="el-icon--right">
                      <arrow-down />
                    </el-icon>
                  </div>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="handleCoreMaterialFilter(1)">
                        <div style="color: #e69103; font-weight: bold">核心件</div>
                      </el-dropdown-item>
                      <el-dropdown-item @click="handleCoreMaterialFilter(0)"
                        >非核心件</el-dropdown-item
                      >
                      <el-dropdown-item @click="handleCoreMaterialFilter(null)"
                        >重置</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
              <template #default="{ row }">
                <div v-if="row.coreMaterials" style="color: #e69103; font-weight: bold">核心件</div>
                <div v-else>非核心件</div>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="store" label="仓库名称" width="104" />
            <!-- <el-table-column show-overflow-tooltip prop="storeType" label="仓库类型" width="104">
              <template #default="i">
                <span>{{ storeType.filter((o) => o.value == i.row.storeType)[0]?.title }}</span>
              </template>
            </el-table-column> -->
            <el-table-column
              show-overflow-tooltip
              prop="storePosition"
              label="仓位名称"
              width="104"
            />
            <el-table-column show-overflow-tooltip prop="unit" label="单位" width="60" />
            <el-table-column
              show-overflow-tooltip
              prop="availableStock"
              width="120"
              :align="'right'"
            >
              <template #header>
                <span style="display: flex; align-items: center">
                  <span>可用库存(数量)</span>
                  <el-tooltip placement="top">
                    <template #content>
                      可用库存 = 即时库存 - 占用库存<br />若开启ERP库存同步
                      则数量以ERP可用库存为准</template
                    >
                    <el-icon>
                      <QuestionFilled />
                    </el-icon>
                  </el-tooltip>
                </span> </template
            ></el-table-column>

            <!-- 在库天数 -->
            <el-table-column label="在库天数" width="80" />
            <!-- <el-table-column
              show-overflow-tooltip
              prop="price"
              label="单价"
              width="90"
              :align="'right'"
            >
              <template #default="scope"> ￥{{ (scope.row.price || 0).toFixed(2) }} </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="totalSum"
              label="金额"
              width="90"
              :align="'right'"
            >
              <template #default="scope"> ￥{{ (scope.row.totalSum || 0).toFixed(2) }} </template>
            </el-table-column> -->
          </el-table>
          <el-table
            v-show="searchVo.selectType == 2"
            :border="true"
            height="100%"
            style="position: absolute"
            stripe
            resizable
            :data="tableDataList"
            show-summary
            :summary-method="(val) => getSummaries(val, [0, 13, 14, 15])"
            @selection-change="handleChange"
            @row-dblclick="goEdit"
          >
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
            <!-- <el-table-column type="selection" width="40" fixed /> -->
            <el-table-column fixed type="index" label="序号" width="49" :align="'center'" />
            <el-table-column show-overflow-tooltip prop="storeCode" label="仓库编号" width="120" />
            <el-table-column show-overflow-tooltip prop="store" label="仓库名称" width="104" />
            <el-table-column show-overflow-tooltip prop="storeType" label="仓库类型" width="104">
              <template #default="i">
                <span>{{ storeType.filter((o) => o.value == i.row.storeType)[0]?.title }}</span>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="storePosition"
              label="仓位名称"
              width="104"
            />
            <el-table-column show-overflow-tooltip prop="goodsCode" label="物料编号" width="110" />
            <el-table-column show-overflow-tooltip prop="goodsName" label="物料名称" width="120" />
            <el-table-column show-overflow-tooltip prop="goodsModel" label="物料型号" width="73" />
            <el-table-column
              show-overflow-tooltip
              prop="goodsSpecName"
              label="物料规格"
              width="97"
            />
            <!-- <el-table-column show-overflow-tooltip prop="goodsType" label="物料类型" width="73">
              <template #default="i">
                <span>{{
                  i.row.goodsType == 1 ? '成品' : i.row.goodsType == 2 ? '物料' : ''
                }}</span>
              </template>
            </el-table-column> -->
            <el-table-column show-overflow-tooltip prop="goodsBrand" label="物料品牌" width="104" />
            <el-table-column show-overflow-tooltip label="物料分类" width="104">
              <template #default="i">
                <span>{{
                  [i.row.type, i.row.twoType, i.row.threeType].filter((o) => o).join('-')
                }}</span>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="unit" label="单位" width="60" />
            <el-table-column
              show-overflow-tooltip
              prop="availableStock"
              width="120"
              :align="'right'"
            >
              <template #header>
                <span style="display: flex; align-items: center">
                  <span>可用库存(数量)</span>
                  <el-tooltip placement="top">
                    <template #content>
                      可用库存 = 即时库存 - 占用库存<br />若开启ERP库存同步
                      则数量以ERP可用库存为准</template
                    >
                    <el-icon>
                      <QuestionFilled />
                    </el-icon>
                  </el-tooltip>
                </span> </template
            ></el-table-column>

            <!-- 在库天数 -->
            <el-table-column label="在库天数" width="120" />

            <!-- <el-table-column
              show-overflow-tooltip
              prop="price"
              label="单价"
              width="90"
              :align="'right'"
            >
              <template #default="scope"> ￥{{ (scope.row.price || 0).toFixed(2) }} </template>
            </el-table-column> -->
            <el-table-column
              show-overflow-tooltip
              prop="totalSum"
              label="金额"
              width="90"
              :align="'right'"
            >
              <template #default="scope"> ￥{{ (scope.row.totalSum || 0).toFixed(2) }} </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <Pagination
            ref="pagination"
            :list_total="total"
            @size-change="getStoneListRows()"
            @current-change="getStoneListRows(false)"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, watch, onMounted, reactive } from 'vue'
  import { RefreshRight, Search } from '@element-plus/icons-vue'
  import { useRoute } from 'vue-router'
  import { brandPageSelect, getGoodsType } from '@/api/goodsInfo'
  import { ElMessage, ElMessageBox, TableColumnCtx } from 'element-plus'
  import { deleteType } from '@/api/basic'
  import { getStockList, getStorePageSelect } from '@/api/store'
  import _, { result } from 'lodash'
  import routeComponentName from '@/config/route-component-name'

  defineOptions({
    name: routeComponentName.storage.invenList,
  })

  const route = useRoute()
  // 部门编辑
  const goEdit = (n: { id: string }) => {
    // router.push('/net/netdetail/' + n.id)
  }
  // 出库仓类型
  const storeType = ref([
    { title: '内部仓库', value: 0 },
    { title: '部门-外部仓库', value: 1 },
    { title: '工程师-外部仓库', value: 2 },
  ])
  const searchVo = ref({
    brandId: '', //	品牌ID
    goodsType: '', //	物料类别：1-成品，2-物料
    keyword: '', //	搜索关键词：物料名称/物料型号/物料规格/编号
    limit: 0,
    page: 0,
    selectType: 1, //	查询类型：1-物料+仓库，2-仓库+物料,示例值(1)
    storeId: '', //	仓库ID
    storeType: '', //	仓库类型：0-内部仓库，1-外部仓库
    threeTypeId: '',
    twoTypeId: '',
    typeId: '',
    storeIds: [],
    coreMaterial: null,
  })
  const ids = ref([])
  function handleChange(val) {
    ids.value = []
    val.filter((o) => {
      ids.value.push(o.id)
    })
  }
  const dayTime = ref('')
  const isTypeId = ref()
  const onSelectGoodTypeTree = (d, n) => {
    if (d.disabled) return
    isTypeId.value = d.id

    searchVo.value = _.cloneDeep({
      brandId: '', //	品牌ID
      goodsType: '', //	物料类别：1-成品，2-物料
      keyword: '', //	搜索关键词：物料名称/物料型号/物料规格/编号
      limit: 0,
      page: 0,
      selectType: 1, //	查询类型：1-物料+仓库，2-仓库+物料,示例值(1)
      storeId: '', //	仓库ID
      storeType: '', //	仓库类型：0-内部仓库，1-外部仓库
      threeTypeId: '',
      twoTypeId: '',
      typeId: '',
      storeIds: [],
      coreMaterial: null,
    })
    switch (n.level) {
      case 1:
        searchVo.value.typeId = d.id
        break
      case 2:
        searchVo.value.typeId = n.parent.data.id
        searchVo.value.twoTypeId = d.id

        break
      case 3:
        searchVo.value.typeId = n.parent.parent.data.id
        searchVo.value.twoTypeId = n.parent.data.id
        searchVo.value.threeTypeId = d.id
        break
      default:
        break
    }
    getStoneListRows()
  }
  // 搜索框下拉数据
  const brandOptions = ref([])
  const getBrandOptionsKeyword = ref('')
  const getBrandOptionsLoading = ref(false)
  const getBrandOptions = async () => {
    getBrandOptionsLoading.value = true
    const data = {
      limit: 0,
      name: getBrandOptionsKeyword.value,
      page: 0,
    }
    const res = await brandPageSelect(data)
    brandOptions.value = res.data.data.rows
    getBrandOptionsLoading.value = false
  }

  // 搜索仓库框下拉数据
  const stoneOptions = ref([])
  const getstoneOptionsKeyword = ref('')
  const getstoneOptionsLoading = ref(false)
  const getstoneOptions = async () => {
    getstoneOptionsLoading.value = true
    const data = {
      limit: 0,
      name: getstoneOptionsKeyword.value,
      page: 0,
    }
    const res = await getStorePageSelect(data)
    stoneOptions.value = res.data.data.rows
    getstoneOptionsLoading.value = false
  }
  const loading = ref(false)
  const total = ref(0)
  const pagination = ref()
  const tableDataList = ref([])
  // 获取部门列表
  const getStoneListRows = (val = true) => {
    if (val) {
      pagination.value?.setPage()
    }
    loading.value = true
    searchVo.value.keyword = searchVo.value.keyword.trim()
    searchVo.value.page = pagination.value?.current // 当面页码
    searchVo.value.limit = pagination.value?.size // 当面页码
    if (searchVo.value.limit >= total.value) {
      searchVo.value.page = 1
    }
    getStockList(searchVo.value).then((res) => {
      if (res.data.code == 20000) {
        tableDataList.value = res.data.data.rows.map((o) => {
          o['totalSum'] = Number(o.price) * Math.abs(Number(o.availableStock))
          return o
        })
        total.value = Number(res.data.data.total)
      } else {
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 5000,
          plain: true,
        })
      }
      loading.value = false
    })
  }
  // 合计
  const getSummaries = (param, arr = []) => {
    const { columns, data } = param
    const sums: string[] = []
    columns.forEach((column, index) => {
      if (arr.includes(index) && (index == 1 || index == 0)) {
        sums[index] = '合计'
        return
      }
      const values = data.map((item) => Number(item[column.property]))
      if (!values.every((value) => Number.isNaN(value))) {
        if (arr.includes(index)) {
          if (index == 13) {
            sums[index] = `${values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!Number.isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)}`
          } else {
            sums[index] = `￥${values
              .reduce((prev, curr) => {
                const value = Number(curr)
                if (!Number.isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              .toFixed(2)}`
          }
        }
      } else {
        sums[index] = ''
      }
    })
    return sums
  }

  /**
   * 核心物料筛选事件
   * @param {boolean} value - 选择的值
   */
  const handleCoreMaterialFilter = (value: 0 | 1 | null) => {
    searchVo.value.coreMaterial = value
    getStoneListRows()
  }

  /**
   * 物料+仓库 表格的合计
   */
  const getGoodAndWarrantySummary = (param: {
    columns: Array<TableColumnCtx<WarehouseStock>>
    data: Array<WarehouseStock>
  }) => {
    const result: Array<string> = []

    result[0] = '合计'

    param.columns.forEach((item, index) => {
      if (item.property === 'availableStock') {
        let num = 0
        param.data.forEach((item) => {
          num += Number(item.availableStock)
        })
        result[index] = num.toString()
      }
    })
    return result
  }

  const dialogVisible = ref(false)
  const edit = ref(false)
  const typeDialogTitle = ref('') // 新增/修改类别弹窗标题
  // 表单数据
  const ruleForm = reactive({
    id: '',
    name: '',
    parentId: '',
    parentName: '',
  })
  const editshow = ref(false)

  const onEditGoodType = (n, d) => {
    typeDialogTitle.value = '编辑分类'
    ruleForm.name = d.name
    ruleForm.id = d.id
    ruleForm.parentName = ''
    if (n.level == 1) {
      ruleForm.parentId = ''
    } else {
      ruleForm.parentId = n.parent.data.id
      ruleForm.parentName = n.parent.data.name
    }
    dialogVisible.value = true
    edit.value = true
  }

  const onDelGoodType = (n, d) => {
    ruleForm.id = d.id
    ElMessageBox({
      type: 'error',
      title: '确认是否删除',
      message: '您确认删除该分类？',
      showCancelButton: true,
    })
      .then(() => {
        deleteType([ruleForm.id]).then((res) => {
          if (res.data.code == 20000) {
            ElMessage({
              message: res.data.message,
              type: 'success',
              plain: true,
              duration: 5000,
              showClose: true,
            })
            getList()
            onReset()
          }
        })
      })
      .catch(() => {
        // 切不可删除该注释，否则会引起eslint的报错
      })
  }

  const defaultProps = {
    children: 'childData',
    label: 'name',
    disabled: 'status',
  }
  const dataType = ref([
    {
      id: 0,
      name: '全部',
      childData: [],
    },
  ])
  const dataTotal = ref([
    {
      id: 1,
      name: '物料+仓库',
    },
    {
      id: 2,
      name: '仓库+物料',
    },
  ])
  // 获取列表数据
  const getList = async () => {
    loading.value = true
    await getGoodsType().then((res) => {
      dataType.value[0].childData = res.data.data.rows
    })
    loading.value = false
  }

  onMounted(() => {
    getList()
    getBrandOptions()
    getStoneListRows()
    getstoneOptions()
    dayTime.value = new Date().toISOString().split('T')[0]
  })

  // 重置事件
  const onReset = () => {
    isTypeId.value = ''
    searchVo.value = _.cloneDeep({
      brandId: '', //	品牌ID
      goodsType: '', //	物料类别：1-成品，2-物料
      keyword: '', //	搜索关键词：物料名称/物料型号/物料规格/编号
      limit: 0,
      page: 0,
      selectType: 1, //	查询类型：1-物料+仓库，2-仓库+物料,示例值(1)
      storeId: '', //	仓库ID
      storeType: '', //	仓库类型：0-内部仓库，1-外部仓库
      threeTypeId: '',
      twoTypeId: '',
      typeId: '',
      coreMaterials: null,
      storeIds: [],
    })
    getStoneListRows()
  }

  watch(route, (value) => {
    if (value.name === 'netList') {
      getStoneListRows()
    }
  })
</script>

<style scoped lang="scss">
  @import './index';
</style>
